<template>
  <c-form-dialog
    label-width="140px"
    title="移动签到"
    ref="form"
    :table-name="tableName"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    submitText="签到"
    @close="beforeClose"
    @success="handleSuccess"
    :visible.sync="innerVisible"
  ></c-form-dialog>
</template>

<script>
import { amapCurrentPosition } from '@vimi/utils-tool'
import { enumSignType } from '@/credit/plugins/enumCadmin'
import { mapGetters } from 'vuex'
export default {
  props: {
    visible: Boolean,
    tableId: String,
    formData: { type: Object, default: () => ({}) },
  },
  data() {
    return {
      innerVisible: false,
      tableName: 'sign_in',
      formItems: [
        {
          tag: 'radio-group',
          itemAttrs: { label: '签到类型：' },
          attrs: { clearable: false, key: 'sign_type', value: '', options: enumSignType },
        },
        {
          tag: 'textarea',
          itemAttrs: { label: '备注说明：' },
          attrs: { key: 'remark', value: '' },
        },
        {
          tag: 'input',
          itemAttrs: { label: '签到地址' },
          attrs: { key: 'address', disabled: true, placeholder: '获取地址中...' },
        },
      ],
    }
  },

  computed: {
    ...mapGetters(['clientId', 'user']),
  },

  watch: {
    visible() {
      this.innerVisible = this.visible
      if (this.visible) {
        this.getAddress()
      }
    },
  },

  created() {},
  methods: {
    handleBeforeSave(data) {
      data.real_name = this.user.realName
      data.user_id = this.user.userId
      data.service_id = this.clientId
      return data
    },
    getAddress() {
      amapCurrentPosition()
        .then(res => {
          this.$nextTick(() => {
            this.$refs.form.setAttrs('address', { value: res?.formattedAddress ?? '' })
          })
        })
        .catch(() => {
          this.$nextTick(() => {
            this.$refs.form.setAttrs('address', { placeholder: '获取地址失败' })
          })
        })
    },
    handleSuccess() {
      this.$emit('success', true)
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped></style>
